﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using AMStudio.Windows.Forms;
using AMStudio.Common;
using AMStudio.Driver;
using AMStudio.DelegateDispather;
using DevComponents.DotNetBar;

namespace AMStudio.UserInterface
{
    public partial class StationUI06 : StationUI
    {
        public StationUI06()
        {
            this.UIName = "StationUI06";
            this.StationIndex = 6;
            InitializeComponent();
        }
        public override bool ActivateUI()
        {
            bool result = base.ActivateUI();

            if (WorkorderDB.ActiveProduct != null)
            {
                this.txtProductName.Text = WorkorderDB.ActiveProduct.Name.ToString();
                this.txtPosJobNO.Text = WorkorderDB.ActiveProduct.St6PositionJobID.ToString();
                this.txtLeftGripperID.Text = WorkorderDB.ActiveProduct.St6LeftGripperToolingID.ToString();
                this.txtRightGripperID.Text = WorkorderDB.ActiveProduct.St6RightGripperToolingID.ToString();
                this.txtECheckToolingID.Text = WorkorderDB.ActiveProduct.St6RightGripperToolingID.ToString();
                this.txtCanDll.Text = WorkorderDB.ActiveProduct.St6CanDll.ToString();
            }
            if (tabControl1.SelectedTabIndex == 4)
            {
                tabItemMaintenace2_Click(tabItemMaintenace2, null);
            }
            return result;
        }

        private void StationUI06_Load(object sender, EventArgs e)
        {
            base.SubscribeEvent("MANAGER_RET");
            base.SubscribeEvent(MachineConfig.Default.St6RobotConfig.HardwareEvent);
            SendMessage("ST6_CONNECT_STATUS", null);
        }

        private void tabControlPanel8_Click(object sender, EventArgs e)
        {

        }
        protected override void SetUserPrivilige(object sender, EventArgs e)
        {
            base.SetUserPrivilige(sender, e);
            User current = UserDB.CurrentLoginUser;
            //Control[] findCtl = null;
            switch (current.AuthorizationSet)
            {
                case 0:
                    this.tabItemMaintenace.Visible = true;
                    this.tabItemMaintenace2.Visible = true;
                    this.tabItemConfiguration.Visible = true;
                    this.tabItemRFTag.Visible = true;
                    this.tabItemIput.Visible = true;
                    this.tabItemOutput.Visible = true;
                    break;
                case 1:
                    this.tabItemMaintenace.Visible = true;
                    this.tabItemMaintenace2.Visible = true;
                    this.tabItemConfiguration.Visible = false;
                    this.tabItemRFTag.Visible = false;
                    this.tabItemIput.Visible = false;
                    this.tabItemOutput.Visible = false;
                    break;
                case 2:
                default:
                    this.tabItemMaintenace.Visible = false;
                    this.tabItemMaintenace2.Visible = false;
                    this.tabItemConfiguration.Visible = false;
                    this.tabItemRFTag.Visible = false;
                    this.tabItemIput.Visible = false;
                    this.tabItemOutput.Visible = false;
                    break;
            }
        }

        protected override void Language_RfreshTag(LanguageItem item)
        {
            base.Language_RfreshTag(item);


            if ((item != null) && (item.Language[LanguageString] != null))
            {
                if (item.ControlName == "tabStrip1")
                {

                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length >= 7)
                    {
                        this.tabItemStatus.Text = titles[0];
                        this.tabItemIput.Text = titles[1];
                        this.tabItemOutput.Text = titles[2];
                        this.tabItemMaintenace.Text = titles[3];
                        this.tabItemMaintenace.Text = titles[4];
                        this.tabItemConfiguration.Text = titles[5];
                        this.tabItemRFTag.Text = titles[6];

                    }
                }
            }
        }
        protected override void Language_InitializeControl(Control UIControl)
        {
            base.Language_InitializeControl(UIControl);

            if (UIControl is StationUI)
            {
                LanguageItem item = LanguageDB.UIDBTags[this.UIName + ".tabStrip1"] as LanguageItem;
                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length >= 7)
                    {
                        this.tabItemStatus.Text = titles[0];
                        this.tabItemIput.Text = titles[1];
                        this.tabItemOutput.Text = titles[2];
                        this.tabItemMaintenace.Text = titles[3];
                        this.tabItemMaintenace2.Text = titles[4];
                        this.tabItemConfiguration.Text = titles[5];
                        this.tabItemRFTag.Text = titles[6];
                    }
                }
            }


        }

        Dictionary<uint, RobotPoint> Points = new Dictionary<uint, RobotPoint>();

        private void btnTrigger_Click(object sender, EventArgs e)
        {
            SendMessage("ECHECK_TRIGGER", null);
        }

        protected override void BackGroud_EventHandler(object sender, StationEventArgs e)
        {
            base.BackGroud_EventHandler(sender, e);

            if (e.From == MachineConfig.Default.St6RobotConfig.HardwareName)
            {
//                 if (e.Status)
//                 {
//                     //CommNGInf.Text = string.Empty;
//                 }
//                 else
//                 {
//                     CommNGInf.Text = e.Value.ToString();
//                 }

                switch (e.Command)
                {
                    case "GET_ALLNOTES":
                        {
                            GetAllPoints.Checked = false;
                            GetAllPoints.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;

                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                                MessageBox.Show(results[1].ToString(), e.Command, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                Dictionary<uint, string> _Notes = (Dictionary<uint, string>)results[1];
                                Dictionary<uint, string>.Enumerator itr = _Notes.GetEnumerator();

                                while (itr.MoveNext())
                                {
                                    if (Points.ContainsKey(itr.Current.Key))
                                    {
                                        Points[itr.Current.Key].Note = itr.Current.Value;
                                    }
                                    else
                                    {
                                        RobotPoint p = new RobotPoint();
                                        p.X = 0;
                                        p.Y = 0;
                                        p.R = 0;
                                        p.Z = 0;
                                        p.A = 0;
                                        p.B = 0;
                                        p.Number = itr.Current.Key;
                                        p.ArmType = 0;
                                        p.Note = itr.Current.Value;
                                        Points.Add(itr.Current.Key, p);
                                    }
                                }

                                PointsListView_RefreshPoints();
                            }
                        }
                        break;

                    case "GET_ASSIGNEDPOINTS":
                        {
                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                                GetAllPoints.Checked = false;
                                GetAllPoints.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
                                MessageBox.Show(results[1].ToString(), e.Command, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                RobotPoint point = (RobotPoint)results[1];

                                if (Points.ContainsKey(point.Number))
                                {
                                    Points[point.Number] = point;
                                }
                                else
                                {
                                    Points.Add(point.Number, point);
                                }

                                SendMessage("ST6_GET_ALLNOTES", null);
                            }
                        }
                        break;

                    case "GET_ALLPOINTS":
                        {
                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                                GetAllPoints.Checked = false;
                                GetAllPoints.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
                                MessageBox.Show(results[1].ToString(), e.Command, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                Dictionary<uint, RobotPoint> _Points = (Dictionary<uint, RobotPoint>)results[1];
                                Dictionary<uint, RobotPoint>.Enumerator itr = _Points.GetEnumerator();

                                Points.Clear();

                                while (itr.MoveNext())
                                {
                                    if (Points.ContainsKey(itr.Current.Key))
                                    {
                                        Points[itr.Current.Key] = itr.Current.Value;
                                    }
                                    else
                                    {
                                        Points.Add(itr.Current.Key, itr.Current.Value);
                                    }
                                }

                                SendMessage("ST6_GET_ALLNOTES", null);
                            }
                        }
                        break;

                    case "WRITE_POINTS":
                    case "SET_POINT":
                    case "TEACH_POINT":
                        {
                            SetSinglePoint.Checked = false;
                            SetSinglePoint.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
                            TeachSinglePoint.Checked = false;
                            TeachSinglePoint.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
                            SetSinglePoint.Enabled = true;
                            TeachSinglePoint.Enabled = true;

                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                                MessageBox.Show(results[1].ToString(), e.Command, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                GetAllPoints_Click(GetAllPoints, null);
                            }
                        }
                        break;

                    case "GET_CURRENT":
                        {
                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                            }
                            else
                            {
                                RobotPoint point = (RobotPoint)results[1];

                                CurrentPosX.Text = point.X.ToString();
                                CurrentPosY.Text = point.Y.ToString();
                                CurrentPosZ.Text = point.Z.ToString();
                                CurrentPosR.Text = point.R.ToString();
                            }
                            IsCircleMsgRevDone2 = true;
                        }
                        break;

                    case "SET_SERVOSTATUS":
                        {
                            SetServo.Checked = false;
                            SetServo.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;

                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                                MessageBox.Show(results[1].ToString(), e.Command, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (IsCircleMsgRevDone1)
                                {
                                    SendMessage("ST6_GET_SERVOSTATUS", null);
                                    IsCircleMsgRevDone1 = false;
                                }
                            }
                        }
                        break;

                    case "GET_SERVOSTATUS":
                        {
                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                            }
                            else
                            {
                                string[] result = results[1].ToString().Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);

                                if (result.Length == 2)
                                {
                                    result[1] = result[1].Trim();

                                    if (result[1].Length == 8)
                                    {
                                        int[] status = new int[4];

                                        for (int i = 0; i < 4; i++)
                                        {
                                            try
                                            {
                                                status[i] = int.Parse(result[1].Substring(7 - i, 1));
                                            }
                                            catch (Exception)
                                            {
                                                break;
                                            }
                                        }
                                        ServoStatusBackColor_Refresh(CheckedServoX, status[0]);
                                        ServoStatusBackColor_Refresh(CheckedServoY, status[1]);
                                        ServoStatusBackColor_Refresh(CheckedServoZ, status[2]);
                                        ServoStatusBackColor_Refresh(CheckedServoR, status[3]);

                                        if (result[1] == "ON")
                                        {
                                            CheckedServoAll.ForeColor = StatusPWR.ForeColor;
                                        }
                                        else
                                        {
                                            CheckedServoAll.ForeColor = Color.Black;
                                        }
                                    }
                                }
                            }
                            IsCircleMsgRevDone1 = true;
                        }
                        break;

                    case "GET_EMGSTATUS":
                        {
                            object[] results = (object[])(((IExecuteReader)e.Value).Result);

                            if (!bool.Parse(results[0].ToString()))
                            {
                            }
                            else
                            {
                                int i = int.Parse(results[1].ToString());

                                if (i == 0)
                                {
                                    EMGStatus.ForeColor = System.Drawing.Color.DarkGray;
                                }
                                else if (i == 1)
                                {
                                    EMGStatus.ForeColor = System.Drawing.Color.Red;
                                }
                            }
                        }
                        break;

                    case "CONNECT_STATUS":
                        {
                            if ((bool)e.Value)
                            {
                                SerialStatus.ForeColor = System.Drawing.Color.Green;
                                SerialSwitch.Checked = true;
                                SerialSwitch.Text = "关闭";
                                SerialSwitch.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2003;
                                DoQuery();
                            }
                            else
                            {
                                SerialStatus.ForeColor = System.Drawing.Color.DarkGray;
                                SerialSwitch.Checked = false;
                                SerialSwitch.Text = "打开";
                                SerialSwitch.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
                            }
                        }
                        break;

                    case "CONNECT":
                        {
                            SerialStatus.ForeColor = System.Drawing.Color.Green;
                            SerialSwitch.Checked = true;
                            SerialSwitch.Text = "关闭";
                            SerialSwitch.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2003;
                        }
                        break;

                    case "DISCONNECT":
                        {
                            SerialStatus.ForeColor = System.Drawing.Color.DarkGray;
                            SerialSwitch.Checked = false;
                            SerialSwitch.Text = "打开";
                            SerialSwitch.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
                        }
                        break;
                }
            }
            else if (e.From == "MANAGER")
            {
                switch (e.Command)
                {
                    case "ECHECK_TRIGGER_RET":
                        this.txtSN.Text = e.Value.ToString();
                        break;
                }
            }
        }

        private void PointsListView_RefreshPoints()
        {
            if (WorkorderDB.ActiveProduct == null)
            {
                return;
            }
            PointsList.Items.Clear();

            Dictionary<uint, RobotPoint> show = new Dictionary<uint, RobotPoint>();
            uint PointNoBegin = (uint)(WorkorderDB.ActiveProduct.St6PositionJobID - 1) * 100;
            for (uint i = PointNoBegin; i < PointNoBegin + 100; i++)
            {
                RobotPoint p = new RobotPoint();
                p.Number = i;
                show.Add(p.Number, p);
            }

            foreach (RobotPoint item in Points.Values)
            {
                if (show.ContainsKey(item.Number))
                {
                    show[item.Number] = item;
                }
            }

            foreach (RobotPoint item in show.Values)
            {
                AMStudio.Windows.Forms.TreeListItem treeItem = new AMStudio.Windows.Forms.TreeListItem(item.Number.ToString());
                if (item.Number == PointNo)
                    treeItem.Checked = true;
                treeItem.SubItems.Add(item.X.ToString());
                treeItem.SubItems.Add(item.Y.ToString());
                treeItem.SubItems.Add(item.Z.ToString());
                treeItem.SubItems.Add(item.R.ToString());
                treeItem.SubItems.Add(item.A.ToString());
                treeItem.SubItems.Add(item.B.ToString());
                treeItem.SubItems.Add(item.Note);
                treeItem.ToolTipText = item.Note;

                PointsList.Items.Add(treeItem);
            }

            if (PointsList.Items.Count >= 1)
            {
                if (PointsList.CheckedItems.Count == 0)
                {
                    PointsList.Items[0].Checked = true;
                    PointNo = uint.Parse(PointsList.Items[0].SubItems[0].Text);
                    TargetPosX.Value = Convert.ToDecimal(PointsList.Items[0].SubItems[1].Text.Trim());
                    TargetPosY.Value = Convert.ToDecimal(PointsList.Items[0].SubItems[2].Text.Trim());
                    TargetPosZ.Value = Convert.ToDecimal(PointsList.Items[0].SubItems[3].Text.Trim());
                    TargetPosR.Value = Convert.ToDecimal(PointsList.Items[0].SubItems[4].Text.Trim());
                }
            }
            PointsList.Invalidate();
        }

        private void ServoStatusBackColor_Refresh(RadioButton bt, int stu)
        {
            switch (stu)
            {
                case 0:
                    bt.ForeColor = StatusOFF.ForeColor;
                    break;
                case 1:
                    bt.ForeColor = StatusON.ForeColor;
                    break;
                case 2:
                    bt.ForeColor = StatusFREE.ForeColor;
                    break;
                default:
                    bt.ForeColor = Color.Transparent;
                    break;
            }
        }

        private void SerialSwitch_Click(object sender, EventArgs e)
        {
            if (SerialSwitch.Checked)
            {
                SendMessage("ST6_ROBOTDRIVER_EXIT", null);
            }
            else
            {
                SendMessage("ST6_ROBOTDRIVER_INIT", null);
            }
        }

        private uint PointNo = 0;
        private void PointsList_TreeItemChecked(object sender, ItemCheckedEventArgs e)
        {
            try
            {
                PointNo = uint.Parse(e.Item.SubItems[0].Text);
                TargetPosX.Value = Convert.ToDecimal(e.Item.SubItems[1].Text.Trim());
                TargetPosY.Value = Convert.ToDecimal(e.Item.SubItems[2].Text.Trim());
                TargetPosZ.Value = Convert.ToDecimal(e.Item.SubItems[3].Text.Trim());
                TargetPosR.Value = Convert.ToDecimal(e.Item.SubItems[4].Text.Trim());
            }
            catch (Exception)
            {
            }

        }

        private void GetAllPoints_Click(object sender, EventArgs e)
        {
            ButtonX Btn = sender as ButtonX;
            if (Btn.Checked)
                return;

            SendMessage("ST6_GET_ALLPOINTS", null);
            Btn.Checked = true;
            Btn.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2003;

        }

        private void TeachSinglePoint_Click(object sender, EventArgs e)
        {
            ButtonX Btn = sender as ButtonX;
            if (Btn.Checked)
                return;

            SetSinglePoint.Enabled = false;

            RobotPoint p = new RobotPoint();
            p.Number = PointNo;
            p.X = Convert.ToSingle(CurrentPosX.Text);
            p.Y = Convert.ToSingle(CurrentPosY.Text);
            p.Z = Convert.ToSingle(CurrentPosZ.Text);
            p.R = Convert.ToSingle(CurrentPosR.Text);

            SendMessage("ST6_SET_POINT", new RobotPoint[] { p });
            Btn.Checked = true;
            Btn.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2003;
        }

        private void timer_CurPos_Tick(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTabIndex != 4 || this.Shell.ActivedUIName != this.UIName)
            {
                timer_CurPos.Enabled = false;
            }
            else
            {
                SendMessage("ST6_CONNECT_STATUS", null);
            }
        }

        private void DoResetUI()
        {
            SetServo.Checked = false;
            SetServo.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
            GetAllPoints.Checked = false;
            GetAllPoints.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
            SetSinglePoint.Checked = false;
            SetSinglePoint.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
            TeachSinglePoint.Checked = false;
            TeachSinglePoint.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2007;
        }

        private void tabItemMaintenace2_Click(object sender, EventArgs e)
        {
            if (!timer_CurPos.Enabled)
            {
                timer_CurPos.Interval = 1000;
                timer_CurPos.Enabled = true;
            }
        }

        private void SetServo_Click(object sender, EventArgs e)
        {
            ButtonX Btn = sender as ButtonX;
            if (Btn.Checked)
                return;

            string status = string.Empty;
            string servo = string.Empty;
            string cmd = string.Empty;

            if (StatusON.Checked)
            {
                status = "ON";
            }
            else if (StatusOFF.Checked)
            {
                status = "OFF";
            }
            else if (StatusFREE.Checked)
            {
                status = "FREE";
            }
            else if (StatusPWR.Checked)
            {
                status = "PWR";
            }

            if (CheckedServoAll.Checked)
            {
            }
            else if (CheckedServoX.Checked)
            {
                servo = "(1)";
            }
            else if (CheckedServoY.Checked)
            {
                servo = "(2)";
            }
            else if (CheckedServoZ.Checked)
            {
                servo = "(3)";
            }
            else if (CheckedServoR.Checked)
            {
                servo = "(4)";
            }

            SendMessage("ST6_SET_SERVOSTATUS", new object[] { status, servo });
            Btn.Checked = true;
            Btn.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2003;
        }

        private void SetSinglePoint_Click(object sender, EventArgs e)
        {
            ButtonX Btn = sender as ButtonX;
            if (Btn.Checked)
                return;

            TeachSinglePoint.Enabled = false;

            RobotPoint p = new RobotPoint();
            p.Number = PointNo;
            p.X = Convert.ToSingle(TargetPosX.Value);
            p.Y = Convert.ToSingle(TargetPosY.Value);
            p.Z = Convert.ToSingle(TargetPosZ.Value);
            p.R = Convert.ToSingle(TargetPosR.Value);

            SendMessage("ST6_SET_POINT", new RobotPoint[] { p });
            Btn.Checked = true;
            Btn.Style = DevComponents.DotNetBar.eDotNetBarStyle.Office2003;
        }

        private bool IsCircleMsgRevDone1 = true;
        private bool IsCircleMsgRevDone2 = true;

        private void DoQuery()
        {
            if (IsCircleMsgRevDone1)
            {
                SendMessage("ST6_GET_SERVOSTATUS", null);
                IsCircleMsgRevDone1 = false;
            }

            if (IsCircleMsgRevDone2)
            {
                SendMessage("ST6_GET_CURRENT", null);
                IsCircleMsgRevDone2 = false;
            }
        }

    }
}
